#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import cexapi
import datetime
import time
import re

import krakenex

showTrue=1
showFalse=0

kraConn = krakenex.API()
kraConn.load_key('kraken.key')


credentialFile = open('credentials.txt', 'r+')

for line in credentialFile:
        resultLine = re.split(';', line)  
        if resultLine[0]=='hannesh':
            apiUser=resultLine[0]
            apiCred1=resultLine[1]
            apiCred2=resultLine[2]      

cexConn = cexapi.api(apiUser, apiCred1, apiCred2)

def balanceKRA(show):
    KRA_balance = kraConn.query_private('Balance')
    ktoEUR = KRA_balance['result']['ZEUR']
    ktoBTC = KRA_balance['result']['XXBT']
    ktoLTC = KRA_balance['result']['XLTC']
    if show:
        print "KraKto: BTC=",ktoBTC, "LTC=",ktoLTC
    return {u'BTC':float(ktoBTC),u'LTC':float(ktoLTC)}
    
def getKraTicker(show):
    kraBitcoin2ltc = kraConn.query_public('Ticker', {'pair':'XXBTXLTC'})
    if show:
        print "KRA sells 1 BTC for",kraBitcoin2ltc['result']['XXBTXLTC']['a'][0], "LTC"
        print "KRA buys  1 BTC for",kraBitcoin2ltc['result']['XXBTXLTC']['b'][0], "LTC"
    return {u'Sells':float(kraBitcoin2ltc['result']['XXBTXLTC']['a'][0]),u'Buys':float(kraBitcoin2ltc['result']['XXBTXLTC']['b'][0])}

def getKraOpenOrders(show):
    openOrdersCount=0    
    try:
        openOrders = kraConn.query_private('OpenOrders', {'pair':'XXBTXLTC'})
        for key in openOrders['result']['open'].keys():                
                type =openOrders['result']['open'][key]['descr']['type']
                price=openOrders['result']['open'][key]['descr']['price']
                volBTC=openOrders['result']['open'][key]['vol']
                order=openOrders['result']['open'][key]['descr']['order']
                openOrdersCount=openOrdersCount+1
                if show:
                    print type, price, volBTC, order
    except:
        print "no open Orders"
    return [openOrdersCount,openOrders]        

def balanceCex(show):
    bal = cexConn.balance()
    if show:
        print "CexKto BTC=",bal['BTC']['available'], "LTC=",bal['LTC']['available']    
    return {u'BTC':float(bal['BTC']['available']),u'LTC':float(bal['LTC']['available'])} 
     
def getCexTicker(show): 
    order_bookLTC = cexConn.order_book("LTC/BTC") 
    ltc_bestBid=float(order_bookLTC['bids'][0][0])  
    ltc_bestAsk=float(order_bookLTC['asks'][0][0])           
    ltcBestBuyPrice=1/ltc_bestAsk
    ltcBestSellPrice=1/ltc_bestBid
    if show:
        print "CEX sells 1 BTC for",ltcBestSellPrice, "\tLTC -> buy LTC @",1/ltcBestSellPrice
        print "CEX buys  1 BTC for",ltcBestBuyPrice, "\tLTC-> sell LTC @",1/ltcBestBuyPrice
    return {u'Sells':ltcBestSellPrice,u'Buys':ltcBestBuyPrice}

def getCexOpenOrders(show):
    openOrdersCount=0
    currOrders = cexConn.current_orders('LTC/BTC')
    sortedCurrOrders = sorted(currOrders, key=lambda order: order['price'], reverse=True)    
    for order in sortedCurrOrders:
        openOrdersCount=openOrdersCount+1
        if show:
            print order
    return [openOrdersCount,sortedCurrOrders]        


counter=100
while True and counter>0:
    counter=counter-1
    
    print "\nStatus"
    balCex=balanceCex(showTrue)    
    tickerCex=getCexTicker(showTrue)
    
    balKra=balanceKRA(showTrue)
    tickerKra=getKraTicker(showTrue)
    
    
    
    openKraOrders=getKraOpenOrders(showFalse)    
    if openKraOrders[0]:        
        for key in openKraOrders[1]['result']['open'].keys():
                print "OPEN ORDERS"                
                #print openOrders['result']['open'][key]
                type =openKraOrders[1]['result']['open'][key]['descr']['type']
                price=openKraOrders[1]['result']['open'][key]['descr']['price']
                volBTC=openKraOrders[1]['result']['open'][key]['vol']
                order=openKraOrders[1]['result']['open'][key]['descr']['order']
                print type, price, volBTC, order
    else:
        print "no open KraOrders"

    openCexOrders=getCexOpenOrders(showFalse)    
    if openCexOrders[0]:
        print openCexOrders[1]
    else:
        print "no open CexOrders"
    
    if (openKraOrders[0] or openCexOrders[0]):
        print "still orders open"
    else:    
        margin=(tickerCex['Buys']/tickerKra['Sells']-1)*100
        if tickerKra['Sells']<tickerCex['Buys'] and margin>0.3:
            print "ARBITRAGE CONDITION buy BTC@KRA(with LTC) sell BTC@CEX(for LTC)"
            print "tickerKra['Sells']<tickerCex['buys']",tickerKra['Sells'],"<",tickerCex['Buys']
            print "margin=",round((tickerCex['Buys']/tickerKra['Sells']-1)*100,2), "%"
            print "propose buy BTC (with LTC) @ Kra and sell @ Cex (for LTC)."
            print "have to transfer LTC from CEX to KRA later, and BTC from KRA to CEX"
            btcVolume=0.1            
            print "place @ Kra amount=",btcVolume, "price=",tickerKra['Sells'],"(", 1/tickerKra['Sells'],")"
            kraConn.query_private('AddOrder', {'pair': 'XXBTXLTC','type': 'buy','ordertype': 'limit','price': tickerKra['Sells'],'volume': btcVolume})       
            print "place @ Cex amount=",btcVolume, "BTC price=",1/tickerCex['Buys'], "(", tickerCex['Buys'], ")"
            cexConn.place_order('buy',btcVolume,1/tickerCex['Buys'],'LTC/BTC')
        else:
            print "no Arbitrage"
            print "margin=",round(margin,2)
            

    print "BTCKRA",balKra['BTC'], "BTCCEX",balCex['BTC'], "LTCKRA=",balKra['LTC'], "LTCCEX=",balCex['LTC']
    print "BTCall=",balKra['BTC']+balCex['BTC'], "LTCall=",balKra['LTC']+balCex['LTC']    
    print "ALL2BTC=",balKra['BTC']+balCex['BTC']+(balKra['LTC']+balCex['LTC'])/tickerKra['Sells']
    
    #k.query_private('AddOrder', {'pair': 'XXBTZEUR',
    #                            'type': 'buy',
    #                             'ordertype': 'limit',
    #                             'price': '100',
    #                            'volume': '0.01'
    #                             })

    #k.query_private('AddOrder', {'pair': 'XXBTZEUR',
    #                           'type': 'sell',
    #                             'ordertype': 'limit',
    #                             'price': '700',
    #                            'volume': '0.01'                            
    #                             })
    
    
    time.sleep(30)